package com.example.fw;

import java.util.regex.Pattern;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;

public abstract class WebDriverHelperBase extends HelperBase
{
	protected WebDriver driver;
	public boolean acceptNextAlert = true;

	public WebDriverHelperBase(ApplicationManager manager)
	{
		super(manager);
		this.driver = manager.getDriver();
	}

	public void type(By locator, String text)
	{
		if (text != null)
		{
			driver.findElement(locator).clear();
			driver.findElement(locator).sendKeys(text);
		}
	}

	public boolean isElementPresent(By locator)
	{
		try
		{
			driver.findElement(locator);
			return true;
		}
		catch (NoSuchElementException e)
		{
			return false;
		}
	}

	public String closeAlertAndGetItsText()
	{
		try
		{
			Alert alert = driver.switchTo().alert();
			if (acceptNextAlert)
			{
				alert.accept();
			}
			else
			{
				alert.dismiss();
			}
			return alert.getText();
		}
		finally
		{
			acceptNextAlert = true;
		}
	}

	protected void click(By locator)
	{
		driver.findElement(locator).click();
	}

	protected void selectByText(By locator, String text)
	{
		if (text != null)
		{
			new Select(driver.findElement(locator)).selectByVisibleText(text);
		}
	}

	protected int size(By locator)
	{
		return driver.findElements(locator).size();
	}

	protected void selectByIndex(By locator, int index)
	{
		new Select(driver.findElement(locator)).selectByIndex(index);
	}

	public static String getCallerName(int depth)
	{
		String callerPath = Thread.currentThread().getStackTrace()[depth].getClassName();
		String[] callerPathSplit = callerPath.split(Pattern.quote("."));
		String r_callerName = callerPathSplit[callerPathSplit.length - 1];

		return r_callerName;
	}

	public static String getPrefix(String prefix)
	{
		try
		{
			if (getCallerName(5).contains("Modification"))
			{
				prefix = "new ";
			}
		}
		catch (Exception ex)
		{
			System.out.println(ex);
		}
		return prefix;
	}

	public void openUrl(String url)
	{
		driver.get(manager.getProperty("baseUrl") + url);
	}

	public void openAbsluteUrl(String url)
	{
		driver.get(url);
	}
}
